//
//  mineViewController.m
//  Protect -A
//
//  Created by 付剑英 on 16/6/15.
//  Copyright © 2016年 付剑英. All rights reserved.
//

#import "mineViewController.h"
#import "baseTableview.h"
#import "MineTableViewCell.h"
#import "baseImageView.h"
#import "LogInViewController.h"
//#import <DKNightVersionManager.h>
//#import <UIView+Night.h>
//#import  <DKColor.h>
#import <DKNightVersion.h>
@interface mineViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,retain)baseTableview *tableview1;
@property (nonatomic, assign) CGFloat cache;/**< 缓存的数值 */
@end

@implementation mineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self create];
    // Do any additional setup after loading the view.
}


#pragma mark - ------------ 创建tableview ---------------

-(void)create{
    
    self.tableview1 = [[baseTableview alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    self.tableview1.delegate = self;
    self.tableview1.dataSource = self;
    
    self.tableview1.dk_backgroundColorPicker = DKColorPickerWithKey(BAR);
    [self.view addSubview: self.tableview1];
    
    [self.tableview1 registerClass:[MineTableViewCell class] forCellReuseIdentifier:@"pool"];
    
    [_tableview1 release];
}
#pragma mark - ------------ 行数 ---------------

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 4;
    }else if (section == 1){
        return 2;
    }else{
        return 1;
    }
}

#pragma mark - ------------ 分区 ---------------

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 3;

}
#pragma mark - ------------ cell赋值 ---------------

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

        UIView *view = [[UIView alloc]init];
        view.dk_backgroundColorPicker = DKColorPickerWithKey(BG);
        return view;

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    
    NSArray *arrLabelName = @[@"我的收藏",@"本地通知",@"夜间模式",@"清除缓存",@"分享给好友",@"帮助与反馈"];
    NSArray *arrImg = @[@"shouCancel",@"bp",@"bn",@"bd",@"bf",@"be"];
    
    //夜间
    cell.dk_backgroundColorPicker = DKColorPickerWithKey(BAR);
   
    
    if (indexPath.section == 0) {
        cell.labelName.text = arrLabelName[indexPath.row];
        cell.img.image = [UIImage imageNamed:arrImg[indexPath.row]];
        switch (indexPath.row) {
            case   1:{
                
                BOOL isPush = [[NSUserDefaults standardUserDefaults]boolForKey:@"isPush"];
                UISwitch *sw = [[UISwitch alloc]initWithFrame:CGRectZero];
                cell.accessoryView = sw;
                sw.on = isPush;
                [sw  addTarget:self action:@selector(switchPost:) forControlEvents:UIControlEventValueChanged];
                
                break;
           
            }
               
                //夜间模式
                
            case 2:{
                
                NSString *night = [[NSUserDefaults standardUserDefaults]objectForKey:@"night"];
                UISwitch *sw = [[UISwitch alloc]initWithFrame:CGRectZero];
                cell.accessoryView = sw;
                
                if ([night isEqualToString:@"yes"]) {
                    sw.on = YES;
                    
                }else{
                   
                    sw.on = NO;
                }
               
                [sw addTarget:self action:@selector(swtichNight:) forControlEvents:UIControlEventValueChanged];
                break;
            }
                
                
                
                
            default:
                break;
        }
    }
    
    if (indexPath.section == 1) {
        cell.labelName.text = arrLabelName[indexPath.row + 4];
        cell.img.image = [UIImage imageNamed:arrImg[indexPath.row + 4]];
    }
    
    
    if(indexPath.section == 2) {
        cell.labelName.text =@"关于";
        cell.img.image = [UIImage imageNamed:@"bg"];
    }

    
    return cell;

}

#pragma mark - ------------ 行高 ---------------
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 40;

}
#pragma mark - ------------ Section 高 ---------------

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        baseImageView *imgeview = [[baseImageView alloc]initWithFrame:CGRectMake(170, 60, 80, 80)];
        imgeview.backgroundColor=[UIColor redColor];
      
       
        imgeview.layer.cornerRadius = 40;
        imgeview.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imgeViewTap:)];
        [imgeview addGestureRecognizer:tap];
        [self.tableview1 addSubview:imgeview];
        return 200;
    }else if (section == 1){
        return 30;
    }else{
        
        return 40;
    }

}

#pragma mark - ------------ 点击登录地点 ---------------
-(void)imgeViewTap:(UITapGestureRecognizer *)tap{

    LogInViewController *vc = [[LogInViewController alloc]init];
    
    [self.navigationController pushViewController:vc animated:YES];
  

}
#pragma mark - ------------ 点击方法 ---------------
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        switch (indexPath.row) {
        
            case 3:
                [self cleanMomery];
                break;
                
            default:
                break;
        }
    }


}

#pragma mark - ------------ 清除内存 ---------------

-(void)cleanMomery{

   //创建管理器对象
    NSFileManager *manager = [NSFileManager defaultManager];
    //获取沙盒
    NSString *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    if ([manager fileExistsAtPath:caches]) {
        NSArray *file = [manager subpathsAtPath:caches];
        //遍历所有文件
        for (NSInteger i = 0; i<file.count; i ++) {
            NSString *filepath = [caches stringByAppendingPathComponent:file[i]];
            //获取文件大小
            CGFloat sizeFile = [[manager attributesOfItemAtPath:filepath error:nil]fileSize];
            self.cache  += sizeFile;
        }
    }
    NSString *messege = [NSString stringWithFormat:@"是否确认清楚%2.1lfM内存",self.cache /1024 / 1024];
    //判断设备系统是否大于8.0
    if ([[[UIDevice currentDevice]systemVersion] floatValue] > 8.0) {
        //提示是否清楚缓存
        UIAlertController *alertView =[UIAlertController alertControllerWithTitle:@"提示" message:messege preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"取消成功");
        }];
        
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //清楚caches文件夹
            NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:path]) {
                NSArray *fileArray = [fileManager subpathsAtPath:path];
                for (NSString *fileName in fileArray) {
                    NSString *cachePath = [path stringByAppendingPathComponent:fileName];
                    [fileManager removeItemAtPath:cachePath error:nil];
                }
            }
            //将缓存值设置为0
            self.cache = 0;
        }];
        
        [alertView addAction:cancel];
        [alertView addAction:ok];
        [self presentViewController:alertView animated:YES completion:nil];
        
    }else{
    
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:nil message:@"系统版本过低无法清楚缓存，请升级系统" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertView animated:YES completion:nil];
        //自动收回
        [self performSelector:@selector(autoBackHome:) withObject:alertView afterDelay:1.5];
    }


}


#pragma mark - ------------ 本地通知 ---------------

-(void)switchPost:(UISwitch *)sw{
  
    if (sw.isOn) {
        //推送
          // 创建一个本地推送
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"isPush"];
        UILocalNotification *notification = [[[UILocalNotification alloc]init]autorelease];
        
        //设置两秒之后
        NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:2];
        if (notification != nil) {
            //设置推送时间
            notification.fireDate = pushDate;
            //设置时区
            notification.timeZone = [NSTimeZone defaultTimeZone];
            //设置重复间隔 每日
            notification.repeatInterval = kCFCalendarUnitDay;
            //推送声音
            notification.soundName = UILocalNotificationDefaultSoundName;
            //推送内容
            notification.alertBody = @"黄鹤老板带着他的小姨子跑了";
            //显示在icon上的红色圈子的数字
            notification.applicationIconBadgeNumber = 1;
            //设置 方便以后撤销之后使用
            NSDictionary *userDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
            
            notification.userInfo = userDic;
            
            //IOS8 之后需要注册 才可授权
            if ([[UIApplication sharedApplication]respondsToSelector:@selector(registerUserNotificationSettings:)]) {
                UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound ;
                UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
                [[UIApplication sharedApplication]registerUserNotificationSettings:settings];
                
            }
            //添加推送到UIApplication
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
  
        }
    
    }else{
           //取消推送
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isPush"];
        //获取 UIApplication
        UIApplication *app = [UIApplication sharedApplication];
        //获取 本地推送数组
        NSArray *arrLocal = [app scheduledLocalNotifications];
        //声明本地通知对象
        UILocalNotification *localNotification = nil;
        
        if (arrLocal) {
            for (UILocalNotification *noti in arrLocal) {
                NSDictionary *dicNoti = noti.userInfo;
                if (dicNoti) {
                    NSString *inkey = [dicNoti objectForKey:@"key"];
                    if ([inkey isEqualToString:@"name"]) {
                        if (localNotification) {
                            [localNotification release];
                            localNotification = nil;
                        }
                        localNotification = [noti retain];
                        break;
                    }
                }
            }
            if (!localNotification) {
                
                //判断是否找到已经存在的相同Key的推送
                localNotification = [[UILocalNotification alloc]init];
                
            }
            if (localNotification) {
                //不推送 取消推送
                [app cancelLocalNotification:localNotification];
               
                [localNotification release];
               
                return;
            }
        }
   
    }

}

#pragma mark - ------------  夜间模式 ---------------

-(void)swtichNight:(UISwitch *)sw{


       
        //夜间
        if ([self.dk_manager.themeVersion isEqualToString:DKThemeVersionNight]) {
            [self.dk_manager  dawnComing];
            [[NSUserDefaults standardUserDefaults]setObject:@"no" forKey:@"Night"];
        }else{
            [self.dk_manager nightFalling];
            [[NSUserDefaults standardUserDefaults]setObject:@"yes" forKey:@"Night"];
        
       
    }
}













#pragma mark - ------------ alert自动收回 ---------------
- (void)autoBackHome:(UIAlertController *)alert
{
    
    [alert dismissViewControllerAnimated:YES completion:nil];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
